package com.zzxy.spring4.factory;

import com.zzxy.spring4.aspect.MyAspect;
import com.zzxy.spring4.service.IStudentService;
import com.zzxy.spring4.service.impl.StudentServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyBaanFactoryCglib {
  public static IStudentService createStudentService(){
    //1.target class
    StudentServiceImpl studentService = new StudentServiceImpl();
    //2.advice
    MyAspect myAspect=new MyAspect();
    //3.weaving
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(studentService.getClass());
    enhancer.setCallback(new MethodInterceptor() {
      @Override
      public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        myAspect.before();
        Object obj = methodProxy.invokeSuper(o,objects);
        myAspect.after();
        return obj;
      }
    });
    return (StudentServiceImpl) enhancer.create();
  }
}
